package com.xu.cloud.auth.component.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xu.cloud.auth.component.PasswordComponent;
import com.xu.cloud.auth.exception.AuthErrorCodeEnum;
import com.xu.cloud.auth.pojo.domain.UserPasswordDO;
import com.xu.cloud.auth.pojo.mapper.UserPasswordMapper;
import com.xu.cloud.common.constant.CryptConstant;
import com.xu.cloud.common.util.AssertUtil;
import com.xu.cloud.common.util.MessageDigestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 密码校验组件实现类
 *
 * @author xuguan
 * @since 2025/2/23
 */
@Slf4j
@Component
public class PasswordComponentImpl implements PasswordComponent {

    public static final String SALT = "XuCloudLoginPasswordSalt";
    public static final String LOGIN_DIGEST_ALGORITHM = CryptConstant.SM3_DIGEST_ALGORITHM;
    @Autowired
    private UserPasswordMapper userPasswordMapper;

    @Override
    public String encryptPassword(String rawPassword) {
        final String encryptPassword = MessageDigestUtil.encryptToHex(rawPassword + SALT, LOGIN_DIGEST_ALGORITHM);
        log.info("加密密码结束, 加密后的密码encryptPassword={}", encryptPassword);
        return encryptPassword;
    }

    @Override
    public boolean checkPassword(Long userId, String rawPassword) {
        log.info("校验密码开始, userId={}", userId);
        AssertUtil.assertNotNull(userId);
        AssertUtil.assertHasText(rawPassword);

        final UserPasswordDO userPasswordDO = userPasswordMapper.selectOne(Wrappers.lambdaQuery(UserPasswordDO.class).eq(UserPasswordDO::getUserId, userId));
        AssertUtil.assertNotNull(userPasswordDO, AuthErrorCodeEnum.PASSWORD_NOT_EXIST.info().newException());
        final String password = userPasswordDO.getPassword();

        final String encryptPassword = encryptPassword(rawPassword);
        log.info("原始加密密码rawPassword={}, 数据库存储加密密码password={}", encryptPassword, password);

        final boolean checkResult = Objects.equals(password, encryptPassword);

        log.info("密码校验结果checkResult={}", checkResult);
        return checkResult;
    }
}
